package com.padgett.resourcemanagement.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;
import com.padgett.resourcemanagement.util.DateUtil;

/**
 * Get Business Client including all services and invoices.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxGetMyServicesServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxGetMyServicesServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String filterCompleted=req.getParameter("FilterCompleted");
		String filterIncomplete=req.getParameter("FilterIncomplete");
		String filterBillable=req.getParameter("FilterBillable");
		String filterNonBillable=req.getParameter("FilterNonBillable");
		boolean completed=(filterCompleted!=null?true:false);
		boolean incomplete=(filterIncomplete!=null?true:false);
		boolean billable=(filterBillable!=null?true:false);
		boolean nonBillable=(filterNonBillable!=null?true:false);
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		List<Entity> entities=ClientDAO.getMyServices(user,completed,incomplete,billable,nonBillable);
		JSONObject response=new JSONObject();
		String errorResponse=null;
		try {
			response.put("success",true);
			response.put("size",entities.size());
			List<JSONObject> services=new ArrayList<JSONObject>();
			Iterator<Entry<String, Object>> iterator=null;
			for(Entity entity:entities){
				Future<Entity> futureClient=ClientDAO.asyncLoadEntity(((Key)(entity.getProperty("Client"))));
				JSONObject service=new JSONObject();
				service.put("serviceId", KeyFactory.keyToString(entity.getKey()));
				iterator=entity.getProperties().entrySet().iterator();
				while(iterator.hasNext()){
					Map.Entry<String, Object> entry=(Map.Entry<String, Object>)iterator.next();
					String entryKey=entry.getKey();
					if(entry.getValue() instanceof Date){
						service.put(entryKey, DateUtil.formatDate(((Date)entry.getValue()), DateUtil.LONG_DATE_FORMAT));
					}else if(entry.getValue() instanceof Text){
						service.put(entryKey, ((Text)entry.getValue()).toString());
					}else{
						service.put(entryKey, entry.getValue());
					}
					if(entryKey.equalsIgnoreCase("accountant")&&entry.getValue()!=null){
						// Get Accountant nickname
						Key accountantKey=new KeyFactory.Builder("User",(String)entry.getValue()).getKey();
						Entity accountant=ClientDAO.loadEntity(accountantKey);
						if(accountant!=null){
							service.put("AccountantName",accountant.getProperty("Nickname"));
						}
					}
				}
				Entity client=null;
				try {
					client = futureClient.get();
					String clientName=(String)(client.getProperty("Name"));
					service.put("ClientName", clientName);
					service.put("ClientId",KeyFactory.keyToString(client.getKey()));
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				services.add(service);
			}
			response.put("data", services);
		} catch (JSONException e) {
			logger.severe(e.getMessage());
			e.printStackTrace();
			errorResponse="{\"success\":false,\"error\":\""+e.getMessage()+"\"}";
		}
		if(errorResponse!=null){
			resp.getWriter().write(errorResponse);
		}else{
			resp.getWriter().write(response.toString());
		}
	}
}
